package com.itheima.service.impl;

import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Override
    public List<User> list() {

        List<User> userList = userDao.findAll();
        for (User user : userList) {

            Long id = user.getId();

            List<Role> roles = roleDao.findRoleByUid(id);

            user.setRoleList(roles);


        }

        return userList;
    }

    @Override
    @Transactional
    public void save(User user, Long[] roleIds) {
        //向user表存储数据
        Long uid = userDao.save(user);
        //int i = 1/0;
        //向中间表存储数据
        userDao.saveUserAndRole(uid,roleIds);
    }

    @Override
    @Transactional
    public void del(Long uid) {

        //删除中间表
        userDao.delUserAndRole(uid);

        //int i = 1/0;
        //删除user表
        userDao.del(uid);
    }

    @Override
    public User login(String username, String password) {
        try {
            User user = userDao.findByUsernameAndPassword(username,password);
            return user;
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
}
